
const defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g;
/**
 * ast 转换成 render函数
 * 
 * <div id="app"> hello {{msg}}<h></h></div>
 * 
 * render(){ _c 解析标签
 *   return _c('div',{id:'app',_v('hello'+_s(msg)),_c})
 * }
 */

/**
 * 处理属性 
 * {id:'app',style:'color:red;font-size:20px'}  
 *  ===>    
 * {id:"app",style:{"color":" red","font-size":" 20px"}}
 * @param {*} attrs 
 */
function genPorps(attrs) {
  let str = '';
  for (let i = 0; i < attrs.length; i++) {
    let attr = attrs[i];
    if (attr.name === 'style') {
      let obj = {};
      attr.value.split(';').forEach(item => {
        let [key, value] = item.split(':');
        obj[key] = value;
      });
      attr.value = obj;
    }
    str += `${attr.name}:${JSON.stringify(attr.value)},`;
  }
  return `{${str.slice(0, -1)}}`;
}

/**
 * 处理子节点
 * @param {*} el 
 */
function genChildren(el) {
  let children = el.children;
  if (children) {
    return children.map(child => gen(child)).join(',');
  }

}
function gen(node) { // 1 元素  3 文本
  if (node.type === 1) {
    return generate(node);
  } else {
    let text = node.text;
    if (!defaultTagRE.test(text)) {
      return `_v(${JSON.stringify(text)})`;
    }
    let tokens = [];
    let lastIndex = defaultTagRE.lastIndex = 0;
    let match;

    while (match = defaultTagRE.exec(text)) {
      let index = match.index;
      if (index > lastIndex) {
        tokens.push(JSON.stringify(text.slice(lastIndex, index)));
      }
      tokens.push(`_s(${match[1].trim()})`);
      lastIndex = index + match[0].length;

    }
    if (lastIndex < text.length) {
      tokens.push(JSON.stringify(text.slice(lastIndex)));
    }
    return `_v(${tokens.join('+')})`
  }
}

export function generate(el) {
  let children = genChildren(el);
  let code = `_c('${el.tag}',${el.attrs.length ? `${genPorps(el.attrs)}` : undefined},${children ? `${children}` : null})`;
  return code;
}